package com.xyd.controller;

import com.xyd.entity.Transaction;
import com.xyd.validate.TransactionValidator;
import org.springframework.stereotype.Controller;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

@RequestMapping("/validate")
@Controller
public class TransactionController {

    @RequestMapping("/validator")
    public ModelAndView annoValidate(@Valid Transaction trans, Errors errors) {
        //是否存在误差
        if (errors.hasErrors()) {
            List<FieldError> errorList = errors.getFieldErrors();

            for (FieldError error : errorList) {
                System.out.println("field:" + error.getField() + "\t" + ",msg" + error.getDefaultMessage());
            }
        }
        return new ModelAndView("test");

    }

    @InitBinder
    public void initBinder(DataBinder binder) {
        binder.setValidator(new TransactionValidator());
    }
}
